//----------------------------头文件依赖----------------------------//
#include "dev_spiflash.h"

/* SFC 最高支持 16M SPI NOR FLASH, 因为 SFC 传输地址是最高支持 3 字节(24位), 故而限制了寻址范围
 * SFC - AHB 总线,最高频率为系统时钟 1 分频; 		SPI - APB 总线,最高频率为系统时钟 2 分频
 */

/**
  \brief   	配置 SFC 模块,初始化 SPI-Flash
  \param [in]   width : 几线通讯
  \return       /
 */
void sfc_config(uint8_t width)
{
    SFC_InitStructure SFC_initStruct;

    /* SFC使用专用的FSPI(Flash SPI)接口连接SPI FLASH */
    PORT_Init(PORTD, PIN5, PORTD_PIN5_FSPI_SCLK, 0);
    PORT_Init(PORTD, PIN6, PORTD_PIN6_FSPI_SSEL, 0);
    PORT_Init(PORTD, PIN8, PORTD_PIN8_FSPI_MOSI, 1);
    PORT_Init(PORTD, PIN7, PORTD_PIN7_FSPI_MISO, 1);
    PORT_Init(PORTD, PIN3, PORTD_PIN3_FSPI_DATA2, 1);
    PORT_Init(PORTD, PIN4, PORTD_PIN4_FSPI_DATA3, 1);

    switch (width)
    {
    case 1:
    default:
        SFC_initStruct.ClkDiv = SFC_CLKDIV_4; // SFC_CLKDIV_2 : 写入SPI-Flash时会影响刷屏
        SFC_initStruct.Cmd_Read = 0x03;
        SFC_initStruct.Width_Read = SFC_RDWIDTH_1;
        SFC_initStruct.Cmd_PageProgram = 0x02;
        SFC_initStruct.Width_PageProgram = SFC_PPWIDTH_1;
        break;

    case 2:
        SFC_initStruct.ClkDiv = SFC_CLKDIV_2;
        SFC_initStruct.Cmd_Read = 0xBB;
        SFC_initStruct.Width_Read = SFC_RDWIDTH_2;
        SFC_initStruct.Cmd_PageProgram = 0x02;
        SFC_initStruct.Width_PageProgram = SFC_PPWIDTH_1;
        break;

    case 4:
        SFC_initStruct.ClkDiv = SFC_CLKDIV_2;
        SFC_initStruct.Cmd_Read = 0xEB;
        SFC_initStruct.Width_Read = SFC_RDWIDTH_4;
        SFC_initStruct.Cmd_PageProgram = 0x32;
        SFC_initStruct.Width_PageProgram = SFC_PPWIDTH_4;
        break;
    }

    SFC_Init(&SFC_initStruct);
	
	if (width > 1 && !SFC_QuadState()) 
		SFC_QuadSwitch(1);// 开启 SPI-Flash 的 Quad_Mode(须查看对应型号 spi-flash 是否支持 Quad 操作)
	
	
	uint32_t spi_flash_id = SFC_ReadJEDEC();
	printf("\r\nSPI-Flash ID = 0x[%x]\r\n", 
	( ( spi_flash_id & 0xFF ) << 16 ) | 
	( ( spi_flash_id & 0xFF00 ) >> 0 ) | 
	( ( spi_flash_id & 0xFF0000 ) >> 16 ));
}
